import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    name: '',     // 用户名
    token: '',    // 登录 token
    id:null,       // 宠物主人id
    avatar: '',   // 头像路径
  }),
  actions: {
    setUserInfo(userInfo) {
      this.name = userInfo.username
      this.token = userInfo.token
      this.id = userInfo.id
      this.avatar = userInfo.avatar

      // 登录成功后同时写入本地存储和会话存储，方便刷新恢复
      localStorage.setItem('username', userInfo.username)
      localStorage.setItem('token', userInfo.token)
      localStorage.setItem('id', userInfo.id)
      localStorage.setItem('avatar', userInfo.avatar || '')
    },

    loadLocalStorage() {
      this.token = localStorage.getItem('token') || sessionStorage.getItem('token') || ''
      this.name = localStorage.getItem('username') || sessionStorage.getItem('username') || ''
      this.id = Number(localStorage.getItem('id')) || null
      this.avatar = localStorage.getItem('avatar') || ''
    },

    clearUserInfo() {
      this.name = ''
      this.token = ''
      this.id = null
      this.avatar = ''

      localStorage.removeItem('token')
      localStorage.removeItem('username')
      localStorage.removeItem('id')
      localStorage.removeItem('avatar')

      sessionStorage.removeItem('token')
      sessionStorage.removeItem('username')
    }
  }
})
